from flask import request, jsonify


from Service import get_month_date, get_year_date



def getPeriodData():
    user_token = request.headers.get('Authorization')
    qy_period = request.form.get("period")
    if qy_period == "week":
        from Service import get_week_date

        qy_week = int(request.form.get("before"))
        started_date, end_date = get_week_date(qy_week)

        try:
            from Controller.login.getJWTandVerify import getUidFromToken
            return statistical_data(started_date, end_date, int(getUidFromToken(user_token)))
        except:
            return "Token过期或服务器异常"

    if qy_period == "month":
        qy_month = int(request.form.get("month"))
        qy_year = int(request.form.get("year"))
        started_date, end_date = get_month_date(qy_year, qy_month)

        try:
            from Controller.login.getJWTandVerify import getUidFromToken
            return statistical_data(started_date, end_date, int(getUidFromToken(user_token)))
        except:
            return "Token过期或服务器异常"

    if qy_period == "year":
        qy_year = int(request.form.get("year"))
        started_date, end_date = get_year_date(qy_year)

        try:
            from Controller.login.getJWTandVerify import getUidFromToken
            return statistical_data(started_date, end_date, int(getUidFromToken(user_token)))
        except:
            return "Token过期或服务器异常"


# # 对数据库的操作，通过uid和date查询日记
def slelectDiaryByDatespanAndUid(qy_startdate, qy_enddate, qy_uid):
    # 传入需要查询的日期，以及uid，返回该日的所有日记数据
    # user_token = request.headers.get('Authorization')
    from Pojo import Diary
    from sqlalchemy import and_
    from sqlalchemy import or_
    diarys = Diary.query.filter(and_(and_(Diary.createdate >= qy_startdate.strftime("%Y-%m-%d"), Diary.createdate <= qy_enddate.strftime("%Y-%m-%d")), Diary.fuid == qy_uid)).all()
    # print(diarys)
    return diarys

# 将在网上存下来的数据存到数据库中
def store_sentence_to_database():
    from Pojo import Proverb
    from Pojo import db

    try:
        from test import read_file
        insert_id = Proverb.query.count() + 1
        for single_proverb in read_file():
            tmp_proverb = Proverb(
                sid = insert_id,
                sentence = single_proverb[0],
                author = single_proverb[1],
            )
            insert_id = insert_id + 1
            db.session.add(tmp_proverb)
            db.session.commit()

        return "好惹"
    except:
        return "上传谚语失败"

# 随机选出谚语
def get_proverb():
    from Pojo import Proverb

    try:
        import random
        qy_id = random.randint(1, Proverb.query.count())
        tmp_proverb = Proverb.query.filter(Proverb.sid == qy_id).first()
        return {
            'sentence': tmp_proverb.sentence,
            'author': tmp_proverb.author,
        }
    except:
        return "选取谚语失败"


def statistical_data(started_date, end_date, user_id):


    diarys = slelectDiaryByDatespanAndUid(started_date, end_date, user_id)

    total_score = 0.0
    toal_num = len(diarys)
    emo_A_dict = {
        'A++心情': 0,
        'A+心情': 0,
        'A心情': 0,
        'A-心情': 0,
        'A--心情': 0,
    }
    # print(store_sentence_to_database())
    # store_sentence_to_database()
    emo_score_map = {'angel': '5', 'angry': '5', 'blink': '25', 'confused': '10', 'cool-1': '20', 'cool': '25',
                     'corpse': '5', 'cry-1': '10', 'cry': '10', 'devil': '15', 'dizzy': '10', 'expressionless-1': '20',
                     'expressionless': '15', 'fall-ill': '15', 'haha-1': '20', 'haha': '20', 'happy-1': '15',
                     'happy-2': '20', 'happy-3': '20', 'injured': '5', 'jealous': '25', 'kiss-1': '25', 'kiss-2': '25',
                     'kiss': '25', 'laughcry': '25', 'love': '25', 'lue-1': '20', 'lue-2': '25', 'lue': '20',
                     'mask': '15', 'muddleb': '20', 'mute': '15', 'poisoning-1': '5', 'poisoning': '10', 'sad-1': '5',
                     'sad-2': '10', 'shocked-1': '15', 'beshocked': '20', 'shut-up': '10', 'sleep': '15',
                     'sly-smile': '25', 'smile-1': '5', 'squint': '10', 'sweating': '5', 'thinking': '10',
                     'tired': '10', 'worry-1': '15', 'worry': '15', 'yue-1': '5', 'yue': '5'}

    emo_convert_map = {
        '5': 'A--心情',
        '10': 'A-心情',
        '15': 'A心情',
        '20': 'A+心情',
        '25': 'A++心情'
    }
    color_pool = ['#f44336', '#ff7043', '#ffca28', '#03a9f4', '#66bb6a']

    emo_top10 = {}

    # 计算平均分、心情top10、A++心情……
    for diary in diarys:
        total_score = total_score + diary.diaryscore
        emo_A_dict[emo_convert_map[emo_score_map[diary.diaryemo]]] += 1
        emo_top10[diary.diaryemo] = emo_top10.get(diary.diaryemo, 0) + 1


    a = dict(sorted(emo_top10.items(), key=lambda x: x[1]))

    top10_dict = {}
    for i, (k, v) in enumerate(a.items()):
        top10_dict[k] = v
        if i == 10:
            break
    A_list = []
    for i, (k, v) in enumerate(emo_A_dict.items()):
        tmp_dict = {
            'name': k,
            'value': v
        }
        A_list.append(tmp_dict)
    top10_x_list = [v for i, (k, v) in enumerate(emo_top10.items())]
    top10_y_list = [k for i, (k, v) in enumerate(emo_top10.items())]

    # print('--------------------------',int(total_score/toal_num), emo_top10, A_list)
    # return "哒哒哒多"
    score = -1 if toal_num == 0 else int(total_score/toal_num)
    if score < 60:
        rtn_color = color_pool[0]
        rtn_comment = "近期情绪极差，建议及时进行心理疏导或与心理医生咨询。很多时候不要一个人硬抗，你的背后有很多人在支持你。"
    elif score>=60 and score<70:
        rtn_color = color_pool[1]
        rtn_comment = '近期心理状态不佳，记得及时调整。很多事情努力了未必有结果，但是不努力却什么改变也没有。你认为自己行就一定行，每天要不断向自己重复。'
    elif score>=70 and score<80:
        rtn_color = color_pool[2]
        rtn_comment = '近期心理状态适中，如果在生活中遇到什么挫折也记得及时和朋友或家人沟通吐槽哦。'
    elif score>=80 and score<90:
        rtn_color = color_pool[3]
        rtn_comment = '近期心理状态良好，请继续保存哦。心理键康与一个人的成就、贡献、成才关系重大，请不要忽视哦。'
    elif score>=90 and score<100:
        rtn_color = color_pool[4]
        rtn_comment = '近期心理状态极佳，一定有一些很开心的事情吧！'
    prover = get_proverb()
    return jsonify({
        'score':  score,
        'color': rtn_color,
        'comment': rtn_comment,
        'content': prover['sentence'],
        'author': prover['author'],
        'pie_data': A_list,
        'horizontal_x': top10_x_list,
        'horizontal_y': top10_y_list,
        'started_date': started_date.strftime("%Y-%m-%d"),
        'end_date': end_date.strftime("%Y-%m-%d")
    })


